package com.jhlishero.study.jdk8.chapter05;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 5.4.1 元素求和
 *    T reduce(T identity, BinaryOperator<T> accumulator);
 *    说明：
 *      · identity：一个初始值，当列表中的值为空时，结果返回该值
 *      · accumulator：将两个元素结合起来产生一个新值
 */
public class Demo5_4_Reduce01 {
    /**
     * 相加
     */
    @Test
    public void testSum01() {
        List<Integer> numberList = new ArrayList<>();
        numberList.add(1);
        numberList.add(3);
        numberList.add(5);
        numberList.add(7);

        int result = numberList.stream().reduce(0, (a, b) -> a + b);
        System.out.println("result=" + result);
    }


    /**
     * 相乘
     */
    @Test
    public void testSum02() {
        List<Integer> numberList = new ArrayList<>();
        numberList.add(1);
        numberList.add(3);
        numberList.add(5);
        numberList.add(7);

        int result = numberList.stream().reduce(1, (a, b) -> a * b);
        System.out.println("result=" + result);
    }


    /**
     * reduce当一个参数时，返回Optional<T>类型
     */
    @Test
    public void testSum03() {
        List<Integer> numberList = new ArrayList<>();
        Optional<Integer> result = numberList.stream().reduce((a, b) -> a * b);
        System.out.println("result=" + result.isPresent()); //如果值存在，则返回true
    }


    /**
     * 获取元素的最大值和最小值
     */
    @Test
    public void testMaxOrMin() {
        List<Integer> numberList = new ArrayList<>();
        numberList.add(1);
        numberList.add(3);
        numberList.add(5);
        numberList.add(7);

        Optional<Integer> min = numberList.stream().reduce(Integer::min);
        min.ifPresent(integer -> System.out.println("min value = " + integer));
        Optional<Integer> max = numberList.stream().reduce(Integer::max);
        max.ifPresent(d -> System.out.println("max value = " + d));
        /*if (max.isPresent()) {
            System.out.println("max value = " + max.get());
        }*/
    }


    /**
     * 拼接字符串
     *
     * 输出结果：
     *      Hello
     *      ,H,e,l,l,o
     */
    @Test
    public void testStr() {
        List<String> strList = new ArrayList<>();
        strList.add("H");
        strList.add("e");
        strList.add("l");
        strList.add("l");
        strList.add("o");

        String result1 = strList.stream().reduce("", (a, b) -> a + "" + b);
        String result2 = strList.stream().reduce("", (a, b) -> a + "," + b);
        System.out.println(result1);
        System.out.println(result2);
    }
}
